package top.easyblog.core.support.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;

/**
 * @author: frank.huang
 * @date: 2023-12-31 16:04
 */
@Slf4j
@Component
public class BatchOperateSupport {

    @Autowired
    private SqlSessionTemplate sqlSession; // MyBatis的SqlSession模板类


    //批量插入大小
    private static final int BATCH_SIZE = 1000;

    public <M, T> void batchInsert(Collection<T> dataList, Class<M> clazz, BiConsumer<M, T> biConsumer) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }

        try (SqlSession session = sqlSession.getSqlSessionFactory().openSession()) {
            M mapper = session.getMapper(clazz);
            Iterator<T> iterator = dataList.iterator();

            for (int i = 0; i < dataList.size(); i++) {
                try {
                    T data = iterator.next();
                    // 手动开始一个新的批处理
                    if ((i % BATCH_SIZE == 0 && i > 0)) {
                        session.commit();
                    }

                    biConsumer.accept(mapper, data);
                } catch (Exception e) {
                    //log.error("Error occurred while inserting data in batch.");
                }
            }

            // 提交整个批处理
            session.commit();
            session.clearCache();
        } catch (Exception e) {
            log.error("Error occurred while inserting data in batch.", e);
        }
    }
}
